package com.soda.servlet;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;

import javax.jms.Session;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import com.soda.bean.Course;
import com.soda.bean.Role;
import com.soda.bean.Student;
import com.soda.bean.User;
import com.soda.dao.CourseDao;
import com.soda.dao.impl.CourseDaoImpl;
import com.soda.service.CourseService;
import com.soda.service.impl.CourseServiceImpl;
import com.soda.util.PageInfo;

public class CourseServlet extends HttpServlet {

	CourseService cs = new CourseServiceImpl();

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		request.setCharacterEncoding("utf-8");
		response.setContentType("text/html;charset=utf-8");
		String param = request.getParameter("param");

		if (param != null) {
			// 分页查 write by LCY
			if ("allCourses".equals(param)) {
				allCourses(request, response);
			}
			// 查询详细信息 write by LCY
			if ("showCourseById".equals(param)) {
				showCourseById(request, response);
			}
			// 编辑信息 write by LCY
			if ("courseUpdate".equals(param)) {
				courseUpdate(request, response);
			}
			// 通过异步改couState write by LCY
			if ("stateUpdate".equals(param)) {
				stateUpdate(request, response);
			}
			// 通过AJAX验证教师是否存在 write by LCY
			if ("selectTname".equals(param)) {
				selectTname(request, response);
			}
			// 添加课程管理 write by LCY
			if ("addCourse".equals(param)) {
				try {

					addCourse(request, response);
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
					
				}
			}
			//查询报名学生的信息                          write by LCY
			if ("showStudents".equals(param)) {
				showStudents(request, response);
			}		
		}
	}

	private void showStudents(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		int id = Integer.parseInt(request.getParameter("id"));
		
		Course c = cs.getCourseById(id);
		
		//System.out.println(c.getCouType());
		if(c.getCouType()==1){
			List<Student> list = cs.selStuByCouType(id);
			PageInfo pi = new PageInfo(1, 4, 0, 0);
			int total=cs.selectTotalStudents(id);
			pi.setTotal(total);
			request.setAttribute("stulist", list);
			request.getSession().setAttribute("page", pi);
			request.getRequestDispatcher("houtai/pages/stu/list.jsp")
			.forward(request, response);
		}else{
			response.sendRedirect("CourseServlet?id="+id+"&param=showCourseById&s=show");
		}
		
		// TODO Auto-generated method stub
		
	}

	private void addCourse(HttpServletRequest request,
			HttpServletResponse response) throws Exception {

		request.setCharacterEncoding("utf-8");
		if (!ServletFileUpload.isMultipartContent(request)) {

			// 如果不是二进制提交的，进行相应处理（重定向到其他页面等）
			return;
		}
		String path = this.getServletContext().getRealPath("video");
		FileItemFactory factory = new DiskFileItemFactory();
		ServletFileUpload upload = new ServletFileUpload(factory);
		upload.setSizeMax(1024 * 1024 * 1000);

		List<FileItem> items = upload.parseRequest(request);
		Course c = new Course();
		for (FileItem item : items) {

			if (item.isFormField()) {
				// 如果是姓名
				if (item.getFieldName().equals("couname")) {
					c.setCouName(item.getString("utf-8"));
				}
				if (item.getFieldName().equals("couaddress")) {
					c.setCouAddress(item.getString("utf-8"));
				}
				if (item.getFieldName().equals("type")) {
					
					c.setCouType(Integer.parseInt(item.getString("utf-8")));
				}
				if (item.getFieldName().equals("coustate")) {
					
					c.setCouState(Integer.parseInt(item.getString("utf-8")));
				}
				if (item.getFieldName().equals("coumoney")) {
					c.setCouMoney(Integer.parseInt(item.getString("utf-8")));
				}
				if (item.getFieldName().equals("otime")) {
					c.setCouOpentime(item.getString("utf-8"));
				}
				if (item.getFieldName().equals("etime")) {
					c.setCouEndtime(item.getString("utf-8"));
				}
				if (item.getFieldName().equals("tname")) {
					User u = cs.getIdAndSelectTeacherName(item
							.getString("utf-8"));
					c.setUser(u);
				}

			} else {
				// 获得文件名
				String fileName = item.getName();
				// 为了防止文件名重复要做一些文件名的唯一处理
				String n = "" + System.currentTimeMillis()
						+ (int) (Math.random() * 100000);
				fileName = n + fileName.substring(fileName.lastIndexOf("."));
				c.setCouVideo(fileName);
				File f = new File(path + "\\" + fileName);
				
				item.write(f);
			}
		}
		// String couname=request.getParameter("couname");
		// String couaddress=request.getParameter("couaddress");
		// int coutype=Integer.parseInt(request.getParameter("type"));
		// int coustate=Integer.parseInt(request.getParameter("coustate"));
		//System.out.println(coustate);
		 // int coumoney=Integer.parseInt(request.getParameter("coumoney"));
		// String otime=request.getParameter("otime");
		// String etime=request.getParameter("etime");
		// String video=request.getParameter("video");

		if (cs.addcourse(c) > 0) {
			// System.out.println("ok");
			request.getRequestDispatcher("CourseServlet?param=allCourses&main=main")
					.forward(request, response);
		}

	}

	private void selectTname(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		response.setContentType("text/html;charset=utf-8");
		PrintWriter out = response.getWriter();
		// 二逼的字符集
		String tname = new String(request.getParameter("tname").getBytes(
				"ISO-8859-1"), "UTF-8");
		// System.out.println(tname);
		User u = cs.getIdAndSelectTeacherName(tname);
		if (u != null) {
			out.print("存在");

		} else {
			out.print("不存在");
		}
	}

	private void stateUpdate(HttpServletRequest request,
			HttpServletResponse response) throws IOException {
		response.setContentType("text/html;charset=utf-8");
		PrintWriter out = response.getWriter();

		int couid = Integer.parseInt(request.getParameter("couid"));
		int coustate = Integer.parseInt(request.getParameter("coustate"));

		// System.out.println(couid+"  "+coustate);

		if (cs.couresStateUpdateById(couid, coustate) > 0) {

		}
	}

	private void courseUpdate(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("utf-8");
		int a = 0;
		int couid = Integer.parseInt(request.getParameter("couid"));
		String couname = request.getParameter("couname");
		String couaddress = request.getParameter("couaddress");
		String coustate = request.getParameter("coustate");
		if ("可报名".equals(coustate)) {
			a = 1;
		}
		if ("报名结束".equals(coustate)) {
			a = 2;
		}
		if ("可购买".equals(coustate)) {
			a = 3;
		}
		if ("已下架".equals(coustate)) {
			a = 4;
		}
		int coumoney = Integer.parseInt(request.getParameter("coumoney"));
		String otime = request.getParameter("otime");
		String etime = request.getParameter("etime");
		String tname = (request.getParameter("tname"));

		User u = cs.getIdAndSelectTeacherName(tname);
		int cc = u.getUseId();

		// Course c=new Course(couid, couname, couaddress,0, a, coumoney, otime,
		// etime, null,null);
		Course c = new Course();
		c.setCouId(couid);
		c.setCouName(couname);
		c.setCouAddress(couaddress);
		c.setCouState(a);
		c.setCouMoney(coumoney);
		if((otime!=null&&otime!="")&&(etime!=null&&otime!="")){
		c.setCouOpentime(otime);
		c.setCouEndtime(etime);
		}
		c.getUser().setUseId(cc);
		if (cs.couUpdate(c) > 0) {

			request.getRequestDispatcher("CourseServlet?param=allCourses")
					.forward(request, response);
		}
	}

	private void showCourseById(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		int id = Integer.parseInt(request.getParameter("id"));
		String s = request.getParameter("s");
		Course c = cs.getCourseById(id);
		request.setAttribute("CourseById", c);
		if ("show".equals(s)) {
			request.getRequestDispatcher("houtai/pages/class/detail.jsp")
					.forward(request, response);
		}
		if ("edit".equals(s)) {
			// System.out.println(c.getCouId());
			request.getRequestDispatcher("houtai/pages/class/edit.jsp")
					.forward(request, response);
		}
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doGet(request, response);
	}

	private void allCourses(HttpServletRequest request,
		HttpServletResponse response) throws ServletException, IOException {
		String couName = request.getParameter("textfield");
		Course couCondition = new Course();
		HttpSession session = request.getSession();
		if (session.getAttribute("couCondition") != null) {

			couCondition = (Course) session.getAttribute("couCondition");
		}
		if (request.getParameter("main") != null) {
			couCondition = new Course();
		}
		if (couName != null) {

			couCondition.setCouName(couName);
		}
		request.getSession().setAttribute("couCondition", couCondition);
		PageInfo pi = new PageInfo(1, 4, 0, 0);
		CourseService cs = new CourseServiceImpl();
		// 查询表格中的总条数
		int total = cs.selectTotalCount(couCondition.getCouName());
		pi.setTotal(total);
		// 根据总条数计算总页数
		// pi.setLastPage((total + pi.getPer() - 1) / pi.getPer());

		String pa = request.getParameter("page");

		if (pa != null) {
			pi.setPage(Integer.parseInt(pa));
		}

		List<Course> list = cs.selectResultByPage(couCondition.getCouName(),
				pi.getPage(), pi.getPer());
		request.setAttribute("cou", list);
		request.setAttribute("page", pi);
		request.getRequestDispatcher("houtai/pages/class/list.jsp").forward(
				request, response);
	}

}
